﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Globalization;

using AjaxPro;
using ECCIT;
using OgilvyOne.Ext.Weibo.Common;
using OgilvyOne.Ext.Weibo.Model;
using OgilvyOne.Ext.Weibo.Lib;
using OgilvyOne.Sharan.Model;
using OgilvyOne.Sharan.IDAL;
using OgilvyOne.Sharan.DALFactory;
using OgilvyOne.Sharan.ProcessFlow;

namespace OgilvyOne.Sharan.BLL
{
    using Microblog_v2 = OgilvyOne.Ext.Weibo.Lib.Microblog;
    using UserInfo_v2 = OgilvyOne.Ext.Weibo.Model.UserInfo;
    using Users_v2 = OgilvyOne.Ext.Weibo.Model.Users;
    using UserIDs_v2 = OgilvyOne.Ext.Weibo.Model.UserIDs;
    using Statuses_v2 = OgilvyOne.Ext.Weibo.Model.Statuses;
    using StatusInfo_v2 = OgilvyOne.Ext.Weibo.Model.StatusInfo;
    using StatusType_v2 = OgilvyOne.Ext.Weibo.Model.StatusType;
    using MicroblogException_v2 = OgilvyOne.Ext.Weibo.Common.MicroblogException;
    using OAuthAccessToken_v2 = OgilvyOne.Ext.Weibo.Common.OAuthAccessToken;

    [AjaxNamespace("WeiboUserBLL")]
    public class WeiboUserBLL
    {
        [AjaxMethod()]
        public List<WeiboUserModel> GetAllWeiboUsers()
        {
            List<WeiboUserModel> users = null;
            try
            {
                users = WeiboUserDALFactory.Create().GetAllWeiboUsers();
            }
            catch (Exception ex)
            {
                users = null;
            }

            return users;
        }

        [AjaxMethod()]
        public ResultInfo Save(WeiboUserModel model)
        {
            return WeiboUserDALFactory.Create().Save(model);
        }

        [AjaxMethod()]
        public ResultInfo Delete(int userID)
        {
            return WeiboUserDALFactory.Create().Delete(userID);
        }

        //private void LoginToWeibo()
        //{
        //    bool login = false;
        //    if (HttpContext.Current.Session["WeiboLoginTime"] != null)
        //    {
        //        DateTime loginTime = (DateTime)HttpContext.Current.Session["WeiboLoginTime"];
        //        if (DateTime.Now.Subtract(loginTime).Minutes < 60)
        //            login = true;
        //    }

        //    if (!login)
        //    {
        //        Microblog_v1.Login(ConfigCacheManager.WeiboAccountName, ConfigCacheManager.WeiboAccountPassword);
        //        HttpContext.Current.Session["WeiboLoginTime"] = DateTime.Now;
        //    }
        //}

        //public string GetUserLatestStatusAboutSharan(string tag)
        //{
        //    try
        //    {
        //        WeiboLogBLL logBll = new WeiboLogBLL();
        //        StringBuilder dataBuilder = new StringBuilder("<users>");

        //        List<WeiboUserModel> users = GetAllWeiboUsers();
        //        int logState = 1;
        //        string errorMsg = null;

        //        ResultInfo result = new ResultInfo(false);
        //        //try
        //        //{
        //        //    LoginToWeibo();
        //        //}
        //        //catch (Exception eLogin)
        //        //{
        //        //    throw new Exception("Error occurred in logon to Sina Weibo. Message: " + eLogin.Message);
        //        //}

        //        foreach (WeiboUserModel user in users)
        //        {
        //            // 判断距离上一次提交请求的时间
        //            //ResultInfo result = logBll.AllowRequestWeiboData(user.ID.Value);
        //            //if (!result.Result)
        //            //{
        //            //    dataBuilder.Append(((WeiboLogModel)result.ReturnObject).RequestResult);
        //            //    continue;
        //            //}

        //            StringBuilder builder = null;
        //            try
        //            {
        //                logState = 1;
        //                //OAuthAccessToken_v1 token = Microblog_v1.Login(user.LoginName, user.Password);
        //                //long userID = long.Parse(token.UserID);
        //                UserInfo_v1 weiboUser = Microblog_v1.GetUserInfo(user.WeiboUserID.Value);
        //                builder = new StringBuilder();

        //                // get template id randomlly
        //                Random r = new Random();
        //                int templateID = r.Next() % ConfigCacheManager.TemplateCount;

        //                builder.AppendFormat("<user id=\"{0}\" screen_name=\"{3}\" name=\"{1}\" profile_image_url=\"{2}\" age=\"{4}\" job=\"{5}\" hobby=\"{6}\" template=\"{7}\">", weiboUser.ID, weiboUser.Name, weiboUser.ProfileImageUrl, weiboUser.ScreenName, user.Age, user.Job, user.Hobby, templateID);
        //                builder.AppendFormat("<statuses>");

        //                bool ended = false;
        //                long? maxID = long.MaxValue;
        //                int foundCount = 0;
        //                while (foundCount < ConfigCacheManager.WeiboPageSize && !ended)
        //                {
        //                    Statuses_v1 statuses = Microblog_v1.GetUserStatuses(weiboUser.ID, null, maxID, null, 20, StatusType_v1.All, false);
                        
        //                    if (statuses.Items.Count < 20)
        //                        ended = true;
        //                    else
        //                        maxID = statuses.Items[statuses.Items.Count - 1].ID;

        //                    foreach (StatusInfo_v1 status in statuses.Items)
        //                    {
        //                        if (status.Text.Contains(tag))
        //                        {
        //                            foundCount++;
        //                            builder.AppendFormat("<status created_at=\"{0}\" bmiddle_pic=\"{1}\" original_pic=\"{2}\" thumbnail_pic=\"{3}\"><![CDATA[{4}]]></status>", FormatTime(status.CreatedAt), status.MiddlePic, status.OriginalPic, status.ThumbnailPic, status.Text);
        //                            if (foundCount == 7)
        //                                break;
        //                        }
        //                    }
        //                }

        //                builder.AppendFormat("</statuses>");
        //                builder.Append("</user>");
        //            }
        //            catch (MicroblogException_v1 exLogin)
        //            {
        //                logState = 2;
        //                errorMsg = exLogin.Message;
        //                builder = new StringBuilder();
        //                if (result.ReturnObject != null)
        //                    builder.Append(((WeiboLogModel)result.ReturnObject).RequestResult);
        //            }

        //            string data = builder.ToString();
        //            dataBuilder.Append(data);
        //            WeiboLogModel log = new WeiboLogModel(null, user.ID, null, DateTime.Now, logState, (logState==1) ? data : errorMsg);
        //            logBll.Insert(log);
        //        }

        //        dataBuilder.Append("</users>");
        //        return dataBuilder.ToString();
        //    }
        //    catch (MicroblogException_v1 mex)
        //    {
        //        // 此处处理用户修改了登录密码导致抛出异常问题，具体方法待讨论
        //        throw mex;
        //    }
        //    catch (Exception ex)
        //    {
        //        throw ex;
        //    }
        //}

        //public string GetSimulateUserLatestStatusAboutSharan_v2(string tag)
        //{
        //    try
        //    {
        //        WeiboLogBLL logBll = new WeiboLogBLL();
        //        StringBuilder dataBuilder = new StringBuilder("<users>");

        //        List<WeiboUserModel> users = GetAllWeiboUsers();
        //        int logState = 1;
        //        string errorMsg = null;

        //        ResultInfo result = new ResultInfo(false);

        //        foreach (WeiboUserModel user in users)
        //        {
        //            // 判断距离上一次提交请求的时间
        //            StringBuilder builder = null;
        //            try
        //            {
        //                logState = 1;
        //                //OAuthAccessToken_v1 token = Microblog_v1.Login(user.LoginName, user.Password);
        //                //long userID = long.Parse(token.UserID);
        //                //UserInfo_v2 weiboUser = Microblog_v2.GetUserInfo(user.WeiboUserID.Value);
        //                UserInfo_v2 weiboUser = new UserInfo_v2();
        //                weiboUser.AvatarLarge = "http://tp4.sinaimg.cn/1079693047/180/1279874663/1";
        //                weiboUser.ID = 1079693047;
        //                weiboUser.Name = "杨艾祥";
        //                weiboUser.ScreenName = weiboUser.Name;
        //                weiboUser.ProfileImageUrl = "";
        //                builder = new StringBuilder();

        //                // get template id randomlly
        //                Random r = new Random();
        //                int templateID = r.Next() % ConfigCacheManager.TemplateCount;

        //                builder.AppendFormat("<user id=\"{0}\" screen_name=\"{3}\" name=\"{1}\" profile_image_url=\"{2}\" age=\"{4}\" job=\"{5}\" hobby=\"{6}\" template=\"{7}\" avatar_large=\"{8}\">", weiboUser.ID, weiboUser.Name, weiboUser.ProfileImageUrl, weiboUser.ScreenName, user.Age, user.Job, user.Hobby, templateID, weiboUser.AvatarLarge);
        //                builder.AppendFormat("<statuses>");

        //                bool ended = false;
        //                long? maxID = long.MaxValue;
        //                int foundCount = 0;
        //                while (foundCount < ConfigCacheManager.WeiboPageSize && !ended)
        //                {
        //                    Statuses_v2 statuses = Microblog_v2.GetUserStatuses(weiboUser.ID, null, maxID, null, 20, StatusType_v2.All, false, false);

        //                    if (statuses.Items.Count < 20)
        //                        ended = true;
        //                    else
        //                        maxID = statuses.Items[statuses.Items.Count - 1].ID;

        //                    foreach (StatusInfo_v2 status in statuses.Items)
        //                    {
        //                        if (status.Text.Contains(tag))
        //                        {
        //                            foundCount++;
        //                            builder.AppendFormat("<status created_at=\"{0}\" bmiddle_pic=\"{1}\" original_pic=\"{2}\" thumbnail_pic=\"{3}\"><![CDATA[{4}]]></status>", FormatTime(status.CreatedAt), status.MiddlePic, status.OriginalPic, status.ThumbnailPic, status.Text);
        //                            if (foundCount == 7)
        //                                break;
        //                        }
        //                    }
        //                }

        //                builder.AppendFormat("</statuses>");
        //                builder.Append("</user>");
        //            }
        //            catch (MicroblogException_v2 exLogin)
        //            {
        //                logState = 2;
        //                errorMsg = exLogin.Message;
        //                builder = new StringBuilder();
        //                if (result.ReturnObject != null)
        //                    builder.Append(((WeiboLogModel)result.ReturnObject).RequestResult);
        //            }

        //            string data = builder.ToString();
        //            dataBuilder.Append(data);
        //            WeiboLogModel log = new WeiboLogModel(null, user.ID, null, DateTime.Now, logState, (logState == 1) ? data : errorMsg);
        //            logBll.Insert(log);
        //        }

        //        dataBuilder.Append("</users>");
        //        return dataBuilder.ToString();
        //    }
        //    catch (MicroblogException_v2 mex)
        //    {
        //        // 此处处理用户修改了登录密码导致抛出异常问题，具体方法待讨论
        //        throw mex;
        //    }
        //    catch (Exception ex)
        //    {
        //        throw ex;
        //    }
        //}

        public string GetUserLatestStatusAboutSharanByAppKey_v2(string tag)
        {
            try
            {
                object obj = HttpContext.Current.Application["CallTime"];
                int callTime = (obj == null) ? 0 : (int)obj;
                HttpContext.Current.Application["CallTime"] = callTime + 1;

                WeiboLogBLL logBll = new WeiboLogBLL();
                StringBuilder dataBuilder = new StringBuilder("<users>");

                List<WeiboUserModel> users = GetAllWeiboUsers();
                int logState = 1;
                string errorMsg = null;

                ResultInfo result = new ResultInfo(false);

                foreach (WeiboUserModel user in users)
                {
                    // 判断距离上一次提交请求的时间
                    StringBuilder builder = null;
                    try
                    {
                        logState = 1;
                        //OAuthAccessToken_v1 token = Microblog_v1.Login(user.LoginName, user.Password);
                        //long userID = long.Parse(token.UserID);
                        UserInfo_v2 weiboUser = Microblog_v2.GetUserInfoByAppkey(user.WeiboUserID.Value);
                        builder = new StringBuilder();

                        // get template id randomlly
                        Random r = new Random();
                        int templateID = r.Next() % ConfigCacheManager.TemplateCount;

                        string age = (user.Age == 0) ? "保密" : user.Age.ToString();
                        builder.AppendFormat("<user id=\"{0}\" screen_name=\"{3}\" name=\"{1}\" profile_image_url=\"{2}\" age=\"{4}\" job=\"{5}\" hobby=\"{6}\" template=\"{7}\" avatar_large=\"{8}\">", weiboUser.ID, weiboUser.Name, weiboUser.ProfileImageUrl, weiboUser.ScreenName, age, user.Job, user.Hobby, templateID, weiboUser.AvatarLarge);
                        builder.AppendFormat("<statuses>");

                        bool ended = false;
                        long? maxID = long.MaxValue;
                        int foundCount = 0;
                        while (foundCount < ConfigCacheManager.WeiboPageSize && !ended)
                        {
                            Statuses_v2 statuses = Microblog_v2.GetUserStatusesByAppKey(weiboUser.ID, null, maxID, null, 50, StatusType_v2.Original, false, false);

                            if (statuses.Items.Count < 50)
                                ended = true;
                            else
                                maxID = statuses.Items[statuses.Items.Count - 1].ID;

                            foreach (StatusInfo_v2 status in statuses.Items)
                            {
                                if (status.Text.Contains(tag))
                                {
                                    foundCount++;
                                    builder.AppendFormat("<status created_at=\"{0}\" bmiddle_pic=\"{1}\" original_pic=\"{2}\" thumbnail_pic=\"{3}\"><![CDATA[{4}]]></status>", FormatTime(status.CreatedAt), WeiboImageReplacer.ReplaceImage(status.MiddlePic), WeiboImageReplacer.ReplaceImage(status.OriginalPic), WeiboImageReplacer.ReplaceImage(status.ThumbnailPic), status.Text);
                                    if (foundCount == 7)
                                        break;
                                }
                            }
                        }

                        builder.AppendFormat("</statuses>");
                        builder.Append("</user>");
                    }
                    catch (MicroblogException_v2 exLogin)
                    {
                        logState = 2;
                        errorMsg = exLogin.Message;
                        builder = new StringBuilder();
                        if (result.ReturnObject != null)
                            builder.Append(((WeiboLogModel)result.ReturnObject).RequestResult);
                    }

                    string data = builder.ToString();
                    dataBuilder.Append(data);
                    WeiboLogModel log = new WeiboLogModel(null, user.ID, null, DateTime.Now, logState, (logState == 1) ? data : errorMsg);
                    logBll.Insert(log);
                }

                dataBuilder.Append("</users>");
                return dataBuilder.ToString();
            }
            catch (MicroblogException_v2 mex)
            {
                // 此处处理用户修改了登录密码导致抛出异常问题，具体方法待讨论
                throw mex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public string GetUserLatestStatusAboutSharan_v2(OAuthAccessToken_v2 accessToken, string tag)
        {
            try
            {
                WeiboLogBLL logBll = new WeiboLogBLL();
                StringBuilder dataBuilder = new StringBuilder("<users>");

                List<WeiboUserModel> users = GetAllWeiboUsers();
                int logState = 1;
                string errorMsg = null;

                ResultInfo result = new ResultInfo(false);

                foreach (WeiboUserModel user in users)
                {
                    // 判断距离上一次提交请求的时间
                    StringBuilder builder = null;
                    try
                    {
                        logState = 1;
                        //OAuthAccessToken_v1 token = Microblog_v1.Login(user.LoginName, user.Password);
                        //long userID = long.Parse(token.UserID);
                        UserInfo_v2 weiboUser = Microblog_v2.GetUserInfo(accessToken, user.WeiboUserID.Value);
                        builder = new StringBuilder();

                        // get template id randomlly
                        Random r = new Random();
                        int templateID = r.Next() % ConfigCacheManager.TemplateCount;

                        string age = (user.Age == 0) ? "保密" : user.Age.ToString();
                        builder.AppendFormat("<user id=\"{0}\" screen_name=\"{3}\" name=\"{1}\" profile_image_url=\"{2}\" age=\"{4}\" job=\"{5}\" hobby=\"{6}\" template=\"{7}\" avatar_large=\"{8}\">", weiboUser.ID, weiboUser.Name, weiboUser.ProfileImageUrl, weiboUser.ScreenName, age, user.Job, user.Hobby, templateID, weiboUser.AvatarLarge);
                        builder.AppendFormat("<statuses>");

                        bool ended = false;
                        long? maxID = long.MaxValue;
                        int foundCount = 0;
                        while (foundCount < ConfigCacheManager.WeiboPageSize && !ended)
                        {
                            Statuses_v2 statuses = Microblog_v2.GetUserStatuses(accessToken, weiboUser.ID, null, maxID, null, 50, StatusType_v2.Original, false, false);

                            if (statuses.Items.Count < 50)
                                ended = true;
                            else
                                maxID = statuses.Items[statuses.Items.Count - 1].ID;

                            foreach (StatusInfo_v2 status in statuses.Items)
                            {
                                if (status.Text.Contains(tag))
                                {
                                    foundCount++;
                                    builder.AppendFormat("<status created_at=\"{0}\" bmiddle_pic=\"{1}\" original_pic=\"{2}\" thumbnail_pic=\"{3}\"><![CDATA[{4}]]></status>", FormatTime(status.CreatedAt), WeiboImageReplacer.ReplaceImage(status.MiddlePic), WeiboImageReplacer.ReplaceImage(status.OriginalPic), WeiboImageReplacer.ReplaceImage(status.ThumbnailPic), status.Text);
                                    if (foundCount == 7)
                                        break;
                                }
                            }
                        }

                        builder.AppendFormat("</statuses>");
                        builder.Append("</user>");
                    }
                    catch (MicroblogException_v2 exLogin)
                    {
                        logState = 2;
                        errorMsg = exLogin.Message;
                        builder = new StringBuilder();
                        if (result.ReturnObject != null)
                            builder.Append(((WeiboLogModel)result.ReturnObject).RequestResult);
                    }

                    string data = builder.ToString();
                    dataBuilder.Append(data);
                    WeiboLogModel log = new WeiboLogModel(null, user.ID, null, DateTime.Now, logState, (logState == 1) ? data : errorMsg);
                    logBll.Insert(log);
                }

                dataBuilder.Append("</users>");
                return dataBuilder.ToString();
            }
            catch (MicroblogException_v2 mex)
            {
                // 此处处理用户修改了登录密码导致抛出异常问题，具体方法待讨论
                throw mex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private string FormatTime(string timeString)
        {
            // Sina weibo time format like: Thu Jan 26 09:29:28 +0800 2012
            string formatString = "ddd MMM dd " + CultureInfo.InvariantCulture.DateTimeFormat.LongTimePattern + " zzz yyyy";
            DateTimeOffset dto;
            if (DateTimeOffset.TryParseExact(timeString,
                                formatString,
                                CultureInfo.InvariantCulture,
                                DateTimeStyles.AllowLeadingWhite,
                                out dto))
                return dto.ToString("yyyy-MM-dd hh:mm:ss");
            else
                return timeString;
        }

        public string GetFriendStatuses(long userID, out string uri)
        {
            try
            {
                // 首先取出当前用户的所有好友用户
                uri = string.Empty;
                WeiboRelationBLL relationBll = new WeiboRelationBLL();
                List<long?> friendIDs = relationBll.GetFriendWeiboUserIDs(userID);
                if (friendIDs == null || friendIDs.Count == 0) return "<users/>";

                AccountController controller = new AccountController();
                StringBuilder builder = new StringBuilder("<users>");
                builder.AppendFormat("<template id=\"{0}\"/>", controller.Random);

                // 把自己这个节点加上
                UserInfo_v2 self = Microblog_v2.GetUserInfo(controller.AccessToken, userID);
                int tryTimes = 0;
                while (self == null && tryTimes < 3)
                {
                    self = Microblog_v2.GetUserInfo(controller.AccessToken, userID);
                    tryTimes++;
                }

                if (self != null)
                    builder.AppendFormat("<user id=\"{0}\" screen_name=\"{3}\" name=\"{1}\" profile_image_url=\"{2}\" avatar_large=\"{4}\" description=\"{5}\"/>", userID, self.Name, self.ProfileImageUrl, self.ScreenName, self.AvatarLarge, self.Description);

                foreach (long? friendID in friendIDs)
                {
                    tryTimes = 0;
                    UserInfo_v2 userInfo = Microblog_v2.GetUserInfo(controller.AccessToken, friendID.Value);
                    while ((userInfo == null || userInfo.LatestStatus == null) && tryTimes < 3)
                    {
                        userInfo = Microblog_v2.GetUserInfo(controller.AccessToken, friendID.Value);
                        tryTimes++;
                    }

                    if (userInfo == null) continue;
                    if (userInfo.LatestStatus == null) continue;

                    StatusInfo_v2 status = userInfo.LatestStatus;
                    builder.AppendFormat("<user id=\"{0}\" screen_name=\"{3}\" name=\"{1}\" profile_image_url=\"{2}\" avatar_large=\"{4}\"", friendID, userInfo.Name, userInfo.ProfileImageUrl, userInfo.ScreenName, userInfo.AvatarLarge);
                    builder.Append(">");
                    builder.AppendFormat("<statuses>");
                    builder.AppendFormat("<status created_at=\"{0}\" bmiddle_pic=\"{1}\" original_pic=\"{2}\" thumbnail_pic=\"{3}\"><![CDATA[{4}]]></status>", FormatTime(status.CreatedAt), status.MiddlePic, status.OriginalPic, status.ThumbnailPic, status.Text);
                    builder.AppendFormat("</statuses>");
                    builder.Append("</user>");
                }
                builder.Append("</users>");

                return builder.ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public Users_v2 GetFriends(long userID, int pageSize, int currentPageIndex, string search)
        {
            AccountController controller = new AccountController();
            Users_v2 users = null;
            Users_v2 pagingUsers = null;

            string prevSearch = controller.Search;
            if (prevSearch != search)
            {
                if (!(string.IsNullOrEmpty(prevSearch) && string.IsNullOrEmpty(search)))
                    currentPageIndex = 0; // 如果发现搜索条件和session中存储条件不同，那么强制将页码清0
            }

            if (string.IsNullOrEmpty(search))
            {
                // 获取分页互粉好友数据
                pagingUsers = Microblog_v2.GetBilateralFriendUsers(controller.AccessToken, userID, pageSize, currentPageIndex + 1, null);
                controller.Search = null;
            }
            else
            {
                // 先判断搜索值是否发生变化
                if (controller.Search == search && controller.Users != null)
                {
                    users = controller.Users;
                }
                else
                {
                    // 获取全部互粉好友数据
                    users = new Users_v2();

                    int pageIndex = 1;
                    while (true)
                    {
                        Users_v2 temp = Microblog_v2.GetBilateralFriendUsers(controller.AccessToken, userID, null, pageIndex, null);

                        foreach (UserInfo_v2 user in temp.Items)
                        {
                            if (user.ScreenName.ToLower().Contains(search.ToLower())        // 判断screen_name是否包含搜索关键字
                                || user.Name.ToLower().Contains(search.ToLower()))      // 判断location是否包含搜索关键字
                            {
                                users.Items.Add(user);
                            }
                        }

                        if (temp.Items.Count < 50) break;
                        pageIndex++;
                    }
                    users.TotalNumber = users.Items.Count;

                    controller.Users = users;
                    controller.Search = search;
                }

                if (users == null) return null;

                // 对users进行分页处理
                pagingUsers = PagingFriends(users, pageSize, currentPageIndex);
            }

            //if (currentPageIndex == 0 && pagingUsers.Items.Count < 7)
            //{
            //    int length = 7 - pagingUsers.Items.Count;
            //    for (int i = 0; i < length; i++)
            //    {
            //        UserInfo_v2 user = new UserInfo_v2();
            //        user.Name = "";
            //        user.ProfileImageUrl = "http://www.sharan.com.cn/weibo/images/avatar_default.jpg";
            //        user.AvatarLarge = user.ProfileImageUrl;
            //        user.ScreenName = user.Name;
            //        user.ID = -1 * i;
            //        users.Items.Add(user);
            //    }
            //}
            return pagingUsers;
        }

        public UserInfo_v2 CreatePersonateUser(long uid, string name, string imageUrl)
        {
            UserInfo_v2 user = new UserInfo_v2();
            user.ID = uid;
            user.Name = name;
            user.ScreenName = name;
            user.ProfileImageUrl = imageUrl;
            user.AvatarLarge = imageUrl;
            return user;
        }

        public Users_v2 PagingFriends(Users_v2 friends, int pageSize, int currentPageIndex)
        {
            int totalRecordCount = friends.Items.Count;
            int iPageSize = pageSize;
            int iCurrentPageIndex = currentPageIndex;

            if (iPageSize == 0) return null;

            int iStartRecordIndex = iPageSize * iCurrentPageIndex;
            int iEndRecordIndex = iPageSize * (iCurrentPageIndex + 1);
            if (iEndRecordIndex > totalRecordCount) iEndRecordIndex = totalRecordCount;

            Users_v2 users = new Users_v2();
            for (int i = iStartRecordIndex; i < iEndRecordIndex; ++i)
                users.Items.Add(friends.Items[i]);

            return users;
        }

        public string GetActiveFollowerStatuses(long userID)
        {
            try
            {
                // 判断距离上一次提交请求的时间
                WeiboLogBLL logBll = new WeiboLogBLL();
                //ResultInfo result = logBll.AllowRequestWeiboData(userID);
                //if (!result.Result && result.ReturnObject != null)
                //    return ((WeiboLogModel)result.ReturnObject).RequestResult;

                // 首先获取登录用户互粉ID列表
                List<UserInfo_v2> foundUsers = new List<UserInfo_v2>();
                UserIDs_v2 userIDs =null;
                try
                {
                    userIDs = Microblog_v2.GetBilateralFriendUserIDs(userID, 2000, null, null);
                }
                catch (Exception e1)
                {
                    throw new Exception("Error occurred in getting bilateral friends. Message:" + e1.Message);
                }

                Users_v2 followers = null;
                try
                {
                    followers = Microblog_v2.GetActiveFollowers(userID, 200);
                }
                catch (Exception e2)
                {
                    throw new Exception("Error occurred in getting active followers. Message:" + e2.Message);
                }

                foreach (UserInfo_v2 follower in followers.Items)
                {
                    if (!userIDs.IDs.Contains(follower.ID)) continue;   // 如果登录用户未关注该用户，continue

                    if (foundUsers.Contains(follower)) continue;        // 如果该用户已经被加入foundUsers列表，contiue

                    foundUsers.Add(follower);

                    if (foundUsers.Count == 6)
                        break;
                }

                foundUsers.Insert(0, Microblog_v2.GetUserInfo(userID)); //将当前登录用户数据加入list

                StringBuilder builder = new StringBuilder("<users>");
                foreach (UserInfo_v2 foundUser in foundUsers)
                {
                    StatusInfo_v2 status = foundUser.LatestStatus;
                    if (status == null)
                        continue;

                    builder.AppendFormat("<user id=\"{0}\" screen_name=\"{3}\" name=\"{1}\" profile_image_url=\"{2}\" avatar_large=\"{4}\"", foundUser.ID, foundUser.Name, foundUser.ProfileImageUrl, foundUser.ScreenName, foundUser.AvatarLarge);
                    if (foundUser.ID == userID)
                        builder.AppendFormat(" description=\"{0}\"", foundUser.Description.Replace("<", "&lt;").Replace(">", "&gt;"));
                    builder.Append(">");
                    builder.AppendFormat("<statuses>");
                    builder.AppendFormat("<status created_at=\"{0}\" bmiddle_pic=\"{1}\" original_pic=\"{2}\" thumbnail_pic=\"{3}\"><![CDATA[{4}]]></status>", FormatTime(status.CreatedAt), status.MiddlePic, status.OriginalPic, status.ThumbnailPic, status.Text);
                    builder.AppendFormat("</statuses>");
                    builder.Append("</user>");
                }
                builder.Append("</users>");

                string output = builder.ToString();

                WeiboLogModel log = new WeiboLogModel(null, null, userID, DateTime.Now, 1, output);
                logBll.Insert(log);

                return output;
            }
            catch (MicroblogException_v2 mex)
            {
                throw mex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}